const usersModel = require('../model/UsersModel')
const moment = require('moment');

class UsersService {
  /**
   * 根据用户名和密码验证用户
   */
  async checkUser(req, res, next) {
    const username = req.body.username
    const password = req.body.password
    try {
      const {results} = await usersModel.checkUser(username, password);
      if (results.length === 0) return res.json({err_code: 1, message: '用户名或密码错误'});
      res.json({
        err_code: 0,
        message: results
      })
    } catch (e) {
      res.json({err_code: 1, message: '意外错误:' + e})
    }
  }

  /**
   * 添加用户
   * 所需参数为 username,password
   */
  async createUser(req, res, next) {
    const body = req.body;
    body.nic_name = '用户' + new Date().getTime()
    body.create_time = moment().format('YYYY-MM-DD HH:mm:ss')

    try { //判断用户是否已经存在
      const isExist = await usersModel.findUserByUserName(body.username);
      if (isExist.results.length >= 1) return res.json({err_code: 1, message: '该账号已注册'})

      //不存在则存入数据库
      const {results} = await usersModel.createUser(body);
      if (results.affectedRows !== 1) return res.json({err_code: 1, message: "注册失败"})
      res.json({
        err_code: 0,
        message: "注册成功"
      })
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }

  /***
   * 根据id修改用户数据
   */
  async updateUserById(req, res, next) {
    const id = req.params.id;
    const body = req.body;

    try {
      const {results} = await usersModel.updateUserById(body, id)
      if (results.affectedRows !== 1) return res.json({err_code: 1, message: '信息编辑失败'})
      res.json({err_code: 0, message: '信息编辑成功'})
    } catch (e) {
      if (e.errno === 1062) return res.json({err_code: 1, message: "该用户名已存在"});
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }

  /***
   * 根据昵称查找用户
   */
  async findUserByNicName(req, res, next) {
    const nic_name = `%${req.query.nic_name}%`;

    try {
      const {results} = await usersModel.findUserByNicName(nic_name)
      res.json({
        err_code: 0,
        message: results
      })
    } catch (e) {
      res.json({err_code: 1, message: "意外错误" + e});
    }
  }
}

module.exports = new UsersService();
